<script lang="ts" setup>
import { ref } from 'vue'
import { formatDateTime } from '@/utils'

const emits = defineEmits(['update:startTime', 'update:endTime'])
const props = defineProps({
    startTime: {
        type: String,
        default: ''
    },
    endTime: {
        type: String,
        default: ''
    }
})
// 显示文字
const title = ref()
// 时间选择映射
const timeRangeMap = {
    '24h': () => new Date(new Date().getTime() - 86400000), // 24小时 = 86400000毫秒
    '7day': () => new Date(new Date().getTime() - 604800000), // 7天 = 604800000毫秒
    '30day': () => {
        const startDate = new Date();
        startDate.setMonth(startDate.getMonth() - 1);
        return startDate;
    },
    '6month': () => {
        const now = new Date();
        const startDate = new Date(now.getFullYear(), now.getMonth() - 6, 1);
        if (startDate.getMonth() + 6 > now.getMonth()) {
            startDate.setFullYear(startDate.getFullYear() - 1);
        }
        return startDate;
    },
    '1year': () => new Date(new Date().getFullYear() - 1, new Date().getMonth(), new Date().getDate())
};
const handleSelectChange = (range: string) => {
    //@ts-ignore
    const timeRangeHandler = timeRangeMap[range];
    const startDate = timeRangeHandler()
    emits('update:startTime', formatDateTime(startDate))
    emits('update:endTime', formatDateTime(new Date()))
};
const selectTime = [
    {
        value: '24h',
        label: '近24小时'
    },
    {
        value: '7day',
        label: '近7天'
    },
    {
        value: '30day',
        label: '近30天'
    },
    {
        value: '6month',
        label: '近半年'
    },
    {
        value: '1year',
        label: '近一年'
    }
]
</script>

<template>
    <jm-select @change="handleSelectChange" style="width: 12.5rem" :startTime="props.startTime" :endTime="props.endTime"
        v-model="title">
        <jm-option v-for="time in selectTime" :key="time.value" :label="time.label" :value="time.value"></jm-option>
    </jm-select>
</template>
<style lang="scss" scoped></style>